<style>
    body {
        font-family: Arial, sans-serif;
        margin: 20px;
    }
    h1, h2 {
        color: #333;
    }
    #appContainer {
        display: flex;
        flex-wrap: wrap;
        margin-top: 20px;
    }

    .button-check {
        padding: 3px 8px;
        background-color: transparent; /* Set background color to transparent */
        color: green; /* Set font color to black */
        border: 1px solid green; /* Set border color to green */
        border-radius: 3px;
        cursor: pointer;
        font-size: 12px; /* Reduce font size */
    }
    .category {
        width: 100%;
        margin-bottom: 20px;
    }
    .app-list {
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-start;
        margin-top: 10px;
    }
    .app-item {
        width: 140px; /* 固定宽度 */
        box-sizing: border-box;
        padding: 5px;
        display: flex;
        align-items: center; 
    }
    .app-item label {
        display: flex;
        align-items: center; 
        width: 100%; 
        text-align: left; 
    }
    input[type="checkbox"],
    input[type="radio"] {
        margin: 0; /* Reset all margins */
        padding: 0; /* Reset padding */
        width: 16px; /* Set a specific width */
        height: 16px; /* Set a specific height */
        border: 1px solid #ccc; /* Add a border */
        border-radius: 3px; /* Add slight rounding */
        background-color: #fff; /* Set background color */
        vertical-align: middle; /* Align vertically in the middle */
        appearance: none; /* Remove default styling */
        position: relative; /* Ensure relative positioning */
    }

    h2 {
        margin-bottom: 10px; 
    }
    .category-title {
        display: flex;
        justify-content: space-between;
        align-items: center; 
        width: 100%;
        cursor: pointer; 
        margin-bottom: 10px; 
    }
    .category-name {
        font-size: 14px; 
        font-weight: normal;
    }
    .arrow {
        width: 12px; 
        height: 12px; 
    

		background-image: url('<%=resource%>/icons/arrow.png'); 
        background-size: contain; 
        background-repeat: no-repeat; 
        transition: transform 0.3s ease; 
        display: inline-block; 
        transform: rotate(0deg); 
    }
    .arrow.expanded {
        transform: rotate(90deg); 
    }
    .category-title div {
        gap: 6px; 
    }

    @media (max-width: 600px) {
        .app-item {
            width: 25%; 
        }
    }

    .button-container {
        display: flex;
        justify-content: right; 
        margin-top: 5px; 
    }

    .submit-button {
        margin-top: 30px;
        width: 150px; 
        height: 30px; 
        background-color: #2885e8;
        color: white;
        border: none;
        border-radius: 5px;
        cursor: pointer;
    }
    .submit-button:hover {
        background-color: #0f77e6;
    }

    .switch {
        position: relative;
        display: inline-block;
        width: 40px;
        height: 20px;
    }

    .switch input {
        opacity: 0;
        width: 0;
        height: 0;
    }

    .slider {
        position: absolute;
        cursor: pointer;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: #ccc;
        transition: .4s;
        border-radius: 20px;
    }

    .slider:before {
        position: absolute;
        content: "";
        height: 16px;
        width: 16px;
        left: 2px;
        bottom: 2px;
        background-color: white;
        transition: .4s;
        border-radius: 50%;
    }

    input:checked + .slider {
        background-color: #2196F3;
    }

    input:checked + .slider:before {
        transform: translateX(20px);
    }

</style>

<script type="text/javascript">//<![CDATA[
	const data2 = {
            "class_list": [
                {
                    "name": "game",
                    "app_list": Array.from({length: 20}, (_, i) => `${1000 + i + 1},App ${i + 1}`)
                },
                {
                    "name": "video",
                    "app_list": Array.from({length: 20}, (_, i) => `${2000 + i + 1},App ${i + 1}`)
                }
            ]
        };

		const data = {
            "class_list": [
                {
                    "name": "game",
                    "app_list": ["1001,app 1","1002,app 2"]
                },
                {
                    "name": "video",
                    	"app_list": ["2001,app 1","2002,app 2"]
                }
            ]
        };
		let app_filter_data = [];
        const selectedAppIds = [1001, 1002, 1003];

		function init_data2() {
			// new XHR().get('<%=url('admin/network/class_list')%>', null,
			// 	function (x, data) {
			// 		console.log(data);
			// 		renderAppList(data);
			// 	}
			// );
			renderAppList(data)
		}

		
		function init_data() {
			getAppFilterData().then(() => {
				getClassListData();
			});
			getAppFilterBaseData(); 
		}

		function getAppFilterData() {
			return new Promise((resolve, reject) => {
				new XHR().get('<%=url('admin/network/get_app_filter')%>', null,
					function (x, data) {
							if (Array.isArray(data.app_list))
						app_filter_data = data.app_list;
						resolve(); 
					}
				);
			});
		}

		function getClassListData() {
			new XHR().get('<%=url('admin/network/class_list')%>', null,
				function (x, data) {
					renderAppList(data);
				}
			);
		}

        function renderAppList(data) {
            const container = document.getElementById('appContainer');
            container.innerHTML = ''; 

            data.class_list.forEach((category, index) => {
                const categoryTitle = document.createElement('div');
                categoryTitle.className = 'category-title'; 

                const categoryName = document.createElement('span');
                categoryName.textContent = `${category.name} (${category.app_list.length}个)`;
                categoryName.className = 'category-name';

                const rightContainer = document.createElement('div');
                rightContainer.style.display = 'flex'; 
                rightContainer.style.alignItems = 'center'; 

                const appCount = document.createElement('span');
                const selectedCount = category.app_list.filter(app => 
                    app_filter_data.includes(parseInt(app.split(',')[0]))
                ).length;
                appCount.textContent = `已选${selectedCount}个`; 
                appCount.className = 'app-count'; 

                const arrow = document.createElement('span');
                arrow.className = 'arrow'; 

                rightContainer.appendChild(appCount);
                rightContainer.appendChild(arrow);

                categoryTitle.appendChild(categoryName);
                categoryTitle.appendChild(rightContainer);
                container.appendChild(categoryTitle);

                const appList = document.createElement('div');
                appList.className = 'app-list';
                
                if (index === 1 || index === 2) {
                    appList.style.display = 'flex';
                    arrow.classList.add('expanded');
                } else {
                    appList.style.display = 'none';
                }

                categoryTitle.onclick = function() {
                    if (appList.style.display === 'none') {
                        appList.style.display = 'flex';
                        arrow.classList.add('expanded');
                    } else {
                        appList.style.display = 'none';
                        arrow.classList.remove('expanded');
                    }
                };

                category.app_list.forEach(app => {
                    const appItem = document.createElement('div');
                    appItem.className = 'app-item';

                    const label = document.createElement('label');

                    const containerDiv = document.createElement('div');
                    containerDiv.style.display = 'flex'; 
                    containerDiv.style.alignItems = 'center';

                    const checkbox = document.createElement('input');
                    checkbox.type = 'checkbox';
                    checkbox.name = 'app';
                    checkbox.value = app.split(',')[0];
                    
                    if (app_filter_data.includes(parseInt(checkbox.value))) {
                        checkbox.checked = true;
                    }

                    const appDetails = app.split(',');
                    const appId = appDetails[0];
                    const appName = appDetails[1];
                    const withIcon = appDetails[2] === '1';

                    const icon = document.createElement('img');
                    icon.src = withIcon ? `<%=resource%>/app_icons/${appId}.png` : `<%=resource%>/app_icons/default.png`; 
                    icon.alt = `Icon for ${appName}`;
                    icon.style.width = '20px'; 
                    icon.style.height = '20px'; 
                    icon.style.marginRight = '5px'; 
                    icon.style.marginLeft = '5px'; 
                    icon.style.borderRadius = '7px';
                    containerDiv.appendChild(checkbox);
                    containerDiv.appendChild(icon);
                    containerDiv.appendChild(document.createTextNode(appName));

                    label.appendChild(containerDiv);
                    appItem.appendChild(label);
                    appList.appendChild(appItem);
                });
                container.appendChild(appList);
            });
        }

        function submitAppSelection() {
            const selectedApps = [];
            const checkboxes = document.querySelectorAll('input[name="app"]:checked');
            checkboxes.forEach(checkbox => {
                selectedApps.push(parseInt(checkbox.value));
            });

            // 将数组转换为逗号分隔的字符串
            const selectedAppsStr = selectedApps.join(',');

            console.log("app_filter_data is " + selectedAppsStr);
            new XHR().post('<%=url('admin/network/set_app_filter')%>', {
                app_list: selectedAppsStr  // 提交字符串而不是数组
            },
            function (x, data) {
                console.log("set ok");
                console.log("set_app_filter data is " + data);
                init_data();
                const modal = document.getElementById('modal');
                modal.style.display = 'flex'; 
                setTimeout(() => {
                    modal.style.display = 'none'; 
                }, 1000);
            }
            );
        }

        function submitAppFilterBase() {
            const filterSwitch = document.getElementById('filterSwitch').checked;
            const workMode = parseInt(document.getElementById('workMode').value, 10);
            const recordSwitch = document.getElementById('recordSwitch').checked;
            const data = {
                data: {
                    enable: filterSwitch ? 1 : 0, 
                    work_mode: workMode,
                    record_enable: recordSwitch ? 1 : 0
                }
            };
            console.log("submitAppFilterBase");
            new XHR().post('<%=url('admin/network/set_app_filter_base')%>', {
                
                enable: filterSwitch ? 1 : 0, 
                work_mode: workMode,
                record_enable: recordSwitch ? 1 : 0
                
            },


            function (x, data) {
                console.log("Base filter settings updated");
            }
            );



        }
 
		function submitHandle() {
			submitAppFilterBase();
			submitAppSelection();
		}

		function openModal() {
			document.getElementById('modal').style.display = 'block';
		}

		function closeModal() {
			document.getElementById('modal').style.display = 'none';
		}

        function getAppFilterBaseData() {
			console.log("getAppFilterBaseData");
            new XHR().get('<%=url('admin/network/get_app_filter_base')%>', null,
                function (x, data) {
                    if (data.data.enable == 1) {
                        document.getElementById('filterSwitch').checked = true;
                    } else {
                        document.getElementById('filterSwitch').checked = false;
                    }
                    if (data.data.record_enable == 1) {
                        document.getElementById('recordSwitch').checked = true;
                    } else {
                        document.getElementById('recordSwitch').checked = false;
                    }
                    document.getElementById('workMode').value = data.data.work_mode;
                }
            );
        }

        function redirectToUserConfig() {
            window.location.href = '<%=url('admin/services/appfilter/user')%>';
        }
        function redirectToTimeConfig() {
            window.location.href = '<%=url('admin/services/appfilter/time')%>';
        }

   
        function updateRunStatus() {
            new XHR().get('<%=url('admin/network/get_oaf_status')%>', null,
                function (x, data) {
                    const runStatusElement = document.getElementById('run_status');
                    const runDescElement = document.getElementById('run_desc');
                    const engineStatusContainer = document.querySelector('.app_filter_status:first-child');

                    if (data.data.engine_status === 1) {
                        if (data.data.config_enable == 0) {
                            runStatusElement.textContent = '未配置';
                            runStatusElement.style.color = 'red';
                        } else {
                            if (data.data.enable === 1) {
                                runStatusElement.textContent = '运行中';
                                runStatusElement.style.color = 'green'; 
                                if (data.data.time_mode == 1 && data.data.filter == 1) {
                                    runDescElement.textContent = `(${data.data.remain_time}分钟后关闭)`;
                                }
                            } else {
                                runStatusElement.textContent = '未运行';
                                runStatusElement.style.color = 'red'; 
                                if (data.data.time_mode == 1) {
                                    if (data.data.match_time == 0) {
                                        runDescElement.textContent = `(当前时间不在时间范围内)`;
                                    } else {
                                        runDescElement.textContent = `(${data.data.remain_time}分钟后开启)`;
                                    }
                                } else {
                                    runDescElement.textContent = `(当前时间不在时间范围内)`;
                                }
                            }
                        }
                    }
                    else{
                        runStatusElement.textContent = '未运行';
                        runStatusElement.style.color = 'red'; 
                        runDescElement.textContent = `(oaf驱动未加载,请下载该固件对应内核版本的oaf.ko驱动文件进行安装，并开启自动加载，当前内核版本为${data.data.kernel_version})`;
                    }
                }
            );
        }

        window.onload = function() {
            init_data();
            updateRunStatus();
            setInterval(updateRunStatus, 5000); 
        };
//]]></script>

<div id="modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); z-index: 1000; justify-content: center; align-items: center;">
    <div style="background-color: rgba(0, 0, 0, 0.5); padding: 10px; border-radius: 5px; text-align: center; width: 100px; height: 70px; color: white; display: flex; justify-content: center; align-items: center;">
        <p style="margin: 0;color: white;">设置成功</p>
    </div>
</div>

<div class="cbi-section cbi-tblsection">
    <div style="max-width: 1000px; margin-left: 5px;padding: 5px;">

        <div class="app_filter_status">
            <label>运行状态:</label>
            <span id="run_status">运行中</span><span id="run_desc"></span>
        </div>
        <div style="margin-top: 10px; display: flex; align-items: center;">
            <label for="filterSwitch" style="margin-right: 5px;">应用过滤</label>
            <label class="switch">
                <input type="checkbox" id="filterSwitch" name="filterSwitch" />
                <span class="slider"></span>
            </label>
            <label for="recordSwitch" style="margin-left: 20px;margin-right: 5px;">应用记录</label>
            <label class="switch">
                <input type="checkbox" id="recordSwitch" name="recordSwitch" />
                <span class="slider"></span>
            </label>
        </div>

        <div style="margin-top: 10px;">
            <label for="workMode">工作模式:</label>
            <select id="workMode" name="workMode">
                <option value="0">网关模式</option>
                <option value="1">旁路模式</option>
            </select>
        </div>
 

        <div style="margin-top: 10px;">
            <span>应用选择:</span>
        </div>
        <div id="appContainer"></div>

        <div style="display: flex; justify-content: flex-start; align-items: center;width: 600px;margin-top: 10px;">
            <div style="width: 280px; display: inline-block;">
                <label>生效时间:</label> 
                <button type="button" class="button-check" onclick="redirectToTimeConfig()">查看</button>
            </div>

            <div style="width: 280px; display: inline-block; margin-left: 10px;">
                <label>生效用户:</label> 
                <!-- <span style="color: green;">5个</span> -->
                <button type="button" class="button-check" onclick="redirectToUserConfig()">查看</button>
            </div>
        </div>
        <div class="button-container">
            <button type="button" class="submit-button" onclick="submitHandle()">保存</button>
        </div>
    </div>
</div>
